
package com.water.wfo.component.spring.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class HttpUtils {

    public static String getUserClientIp() {
        ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != req && null != req.getRequest()){
            HttpServletRequest request1 = req.getRequest();
            return getUserClientIp(request1);
        }
        return null ;
    }

    public static String getUserClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null) {
            String[] ipList = ip.split(",");
            ip = ipList[0].trim();
        }

        return ip;
    }
    public static String getReferer(HttpServletRequest request) {
        return request.getHeader("referer");
    }

    public static String getCurrentServiceIp() {
        String ipAddress = null;

        try {
            ipAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException var2) {

        }

        return ipAddress;
    }
}
